package prog.view;

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
import prog.model.Project;
import prog.Main;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.io.File;
import java.io.IOException;
import java.net.URI;
import javax.swing.*;
import javax.swing.event.HyperlinkEvent;
import javax.swing.event.HyperlinkListener;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeCellRenderer;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreePath;
/*
 * WorkAreaPanel.java
 *
 * Created on Jan 8, 2011, 5:04:43 PM
 */

/**
 *
 * @author MrKhoai
 */
public class WorkAreaPanel extends javax.swing.JPanel {
    private DefaultMutableTreeNode project = null;
    private DefaultTreeModel model = null;
    /** Creates new form WorkAreaPanel */
    public WorkAreaPanel() {
        initComponents();
        addListenner();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {
        java.awt.GridBagConstraints gridBagConstraints;

        mn_popup = new javax.swing.JPopupMenu();
        mni_removeProject = new javax.swing.JMenuItem();
        mni_removeProject.setIcon(new javax.swing.ImageIcon("resource/tool/Delete.png"));
        jSplitPane1 = new javax.swing.JSplitPane();
        jTabbedPane1 = new javax.swing.JTabbedPane();
        jPanel1 = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTree1 = createTree();
        jPanel2 = new javax.swing.JPanel();
        jPanel3 = new javax.swing.JPanel();
        lb_projectName = new javax.swing.JLabel();
        lb_projectName.setFont(lb_projectName.getFont().deriveFont(Font.TYPE1_FONT, 16));
        lb_dst = new javax.swing.JLabel();
        lb_dst.setFont(lb_dst.getFont().deriveFont(Font.TYPE1_FONT, 15));
        lb_url = new javax.swing.JLabel();
        lb_url.setFont(lb_url.getFont().deriveFont(16));

        mni_removeProject.setText("Hủy dự án");
        mni_removeProject.setActionCommand("removeProject");
        mn_popup.add(mni_removeProject);

        jTabbedPane1.setMinimumSize(new java.awt.Dimension(250, 200));

        jPanel1.setPreferredSize(new java.awt.Dimension(245, 356));

        jTree1.setShowsRootHandles(true);
        jScrollPane1.setViewportView(jTree1);

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 245, Short.MAX_VALUE)
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 300, Short.MAX_VALUE)
        );

        jTabbedPane1.addTab("Dự án", jPanel1);

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 245, Short.MAX_VALUE)
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 300, Short.MAX_VALUE)
        );

        jTabbedPane1.addTab("Thư mục", jPanel2);

        jSplitPane1.setLeftComponent(jTabbedPane1);

        jPanel3.setMinimumSize(new java.awt.Dimension(200, 200));
        jPanel3.setLayout(new java.awt.GridBagLayout());
        jPanel3.add(lb_projectName, new java.awt.GridBagConstraints());
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 1;
        jPanel3.add(lb_dst, gridBagConstraints);
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 2;
        jPanel3.add(lb_url, gridBagConstraints);

        jSplitPane1.setRightComponent(jPanel3);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jSplitPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 440, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jSplitPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 330, Short.MAX_VALUE)
        );
    }// </editor-fold>//GEN-END:initComponents

    protected javax.swing.JTree createTree() {
        MyCellRenderer cell = new MyCellRenderer();
        DefaultMutableTreeNode top = new DefaultMutableTreeNode();
        project = new DefaultMutableTreeNode("Dự án");
        top.add(project);
        Main.program.loadInstance();
        int count  = Main.program.getProjectCount();
        for(int i = 0; i < count; i++) {
            DefaultMutableTreeNode pj = new DefaultMutableTreeNode(Main.program.getProject(i).getName());
            project.add(pj);
        }
        model = new DefaultTreeModel(top);
        javax.swing.JTree tree = new JTree(model);
        tree.setCellRenderer(cell);
        tree.setRootVisible(false);
        tree.expandRow(0);
        return tree;
    }

    public void reloadTree() {
        int row = jTree1.getRowForPath(jTree1.getSelectionPath());
        model.reload();
        jTree1.expandRow(0);
        jTree1.setSelectionRow(row);
    }

    protected void addListenner() {
        MyListenner listenner = new MyListenner();
        jTree1.addTreeSelectionListener(listenner);
        jTree1.addMouseListener(listenner);
        mni_removeProject.addActionListener(listenner);
        lb_url.addMouseListener(listenner);
    }

    public void addProject(Project pj) {
        project.add(new DefaultMutableTreeNode(pj.getName()));
        model.reload();
        jTree1.expandRow(0);
        Main.program.newProject(pj);
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JSplitPane jSplitPane1;
    private javax.swing.JTabbedPane jTabbedPane1;
    public javax.swing.JTree jTree1;
    private javax.swing.JLabel lb_dst;
    private javax.swing.JLabel lb_projectName;
    private javax.swing.JLabel lb_url;
    private javax.swing.JPopupMenu mn_popup;
    private javax.swing.JMenuItem mni_removeProject;
    // End of variables declaration//GEN-END:variables

    private class MyListenner implements TreeSelectionListener, MouseListener, ActionListener {

        public void valueChanged(TreeSelectionEvent e) {
            TreePath path = e.getPath();
            int index = jTree1.getRowForPath(path);
            if(index > 0) {
                Project pj = Main.program.getProject(index - 1);
                
                lb_url.setText("<HTML><FONT color=\"#000099\"><U>"+ pj.getURL() +"</U></FONT></HTML>");
                lb_projectName.setText(pj.getName());
                lb_dst.setText(pj.getDst());
                int status = pj.getStatus();
                
                if(status == Project.RUN) {
                    Main.program.mainForm.pnToolbar.bt_startDown1.setEnabled(false);
                    
                    Main.program.mainForm.pnToolbar.bt_pauseDown1.setEnabled(true);
                    Main.program.mainForm.pnToolbar.bt_stopDown1.setEnabled(true);

                    Main.program.mainForm.pnToolbar.bt_pauseDown1.setText("Tạm dừng");
                    Main.program.mainForm.pnToolbar.bt_pauseDown1.setIcon(new ImageIcon("resource/tool/SupendDown.png"));
                }

                if(status == Project.PAUSE || status == Project.STOP) {
                    Main.program.mainForm.pnToolbar.bt_startDown1.setEnabled(true);
                    Main.program.mainForm.pnToolbar.bt_pauseDown1.setEnabled(true);

                    Main.program.mainForm.pnToolbar.bt_stopDown1.setEnabled(false);

                    Main.program.mainForm.pnToolbar.bt_pauseDown1.setText("Tiếp tục");
                    Main.program.mainForm.pnToolbar.bt_pauseDown1.setIcon(new ImageIcon("resource/tool/ResumeDown.png"));
                }

                if(status == Project.NONE || status == Project.FINISHED) {
                    Main.program.mainForm.pnToolbar.bt_startDown1.setEnabled(true);

                    Main.program.mainForm.pnToolbar.bt_pauseDown1.setEnabled(false);
                    Main.program.mainForm.pnToolbar.bt_stopDown1.setEnabled(false);

                    Main.program.mainForm.pnToolbar.bt_pauseDown1.setText("Tạm dừng");
                    Main.program.mainForm.pnToolbar.bt_pauseDown1.setIcon(new ImageIcon("resource/tool/SupendDown.png"));

                }
            }
            else {
                Main.program.mainForm.pnToolbar.bt_startDown1.setEnabled(false);
                Main.program.mainForm.pnToolbar.bt_pauseDown1.setEnabled(false);
                Main.program.mainForm.pnToolbar.bt_stopDown1.setEnabled(false);
                lb_url.setText(null);
                lb_projectName.setText(null);
                lb_dst.setText(null);
            }
        }

        public void mouseClicked(MouseEvent e) {
            if(e.getSource().equals(lb_url)) {
                TreePath path = jTree1.getSelectionPath();
                int index = jTree1.getRowForPath(path);
                Project pj = Main.program.getProject(index - 1);
                String url = pj.getURL();
                lb_url.setText("<HTML><FONT color=\"#000040\"><U><I>" + url +"</I></U></FONT></HTML>");
                String dst = pj.getDst();
                int pos = url.indexOf("//");
                url = url.substring(pos +2);
                String[] regex = url.split("/");

                if(regex.length > 0) {
                    String fname = regex[regex.length-1] + ".html";
                    String fpath = dst + regex[0] + '/' + fname;
                    try {
                        Runtime.getRuntime().exec(new String[] {"cmd", "/c", fpath});
                    }
                    catch(IOException ex) {

                    }
                }
            }
        }

        public void mouseEntered(MouseEvent e) {
            if(e.getSource().equals(lb_url)) {
                TreePath path = jTree1.getSelectionPath();
                int index = jTree1.getRowForPath(path);
                Project pj = Main.program.getProject(index - 1);
                String url = pj.getURL();
                lb_url.setText("<HTML><FONT color=\"#000099\"><U><I>"+ url +"</I></U></FONT></HTML>");
            }
        }

        public void mouseExited(MouseEvent e) {
            if(e.getSource().equals(lb_url)) {
                TreePath path = jTree1.getSelectionPath();
                int index = jTree1.getRowForPath(path);
                Project pj = Main.program.getProject(index - 1);
                String url = pj.getURL();
                lb_url.setText("<HTML><FONT color=\"#000099\"><U>"+ url +"</U></FONT></HTML>");
            }
        }

        public void mousePressed(MouseEvent e) {
            if(e.getSource().equals(jTree1)) {
                if(e.getButton() == 3) {
                    int x = e.getX();
                    int y = e.getY();
                    TreePath path = jTree1.getPathForLocation(x, y);
                    int row = jTree1.getRowForPath(path);
                    if(row > 0) {
                        int[] rows = jTree1.getSelectionRows();
                        if(rows == null)
                            jTree1.setSelectionRow(row);
                        else {
                            boolean flag = false;
                            for(int r:rows) {
                                if(r == row)
                                    flag = true;
                            }
                            if(!flag)
                                jTree1.setSelectionRow(row);
                        }

                        mn_popup.show(jTree1, x, y);
                    }
                }

                if(e.getButton() == 1) {
                    int x = e.getX();
                    int y = e.getY();
                    TreePath path = jTree1.getPathForLocation(x, y);
                    int row = jTree1.getRowForPath(path);
                    if(row == 0)
                        jTree1.setSelectionRow(row);
                    int[] rows = jTree1.getSelectionRows();
                    if(rows != null) {
                        int[] rowselection = new int[rows.length - 1];
                        if(rows[0] == 0) {
                            for(int i = 0; i < rowselection.length; i++ )
                                rowselection[i] = rows[i+1];
                            jTree1.setSelectionRows(rowselection);
                        }
                    }
                }
            }
        }

        public void mouseReleased(MouseEvent e) {}

        public void actionPerformed(ActionEvent e) {
            String actionCommand = e.getActionCommand();
            if(actionCommand.equals("removeProject")) {
                int[] rows = jTree1.getSelectionRows();
                for(int i = 0; i < rows.length - 1; i++) {
                    for(int j = i + 1; j < rows.length; j++)
                        if(rows[i] < rows[j]) {
                            int temp = rows[i];
                            rows[i] = rows[j];
                            rows[j] = temp;
                        }
                }
                for(int r : rows) {
                    Main.program.removeProject(r-1);
                    project.remove(r-1);
                }
                model.reload(project);
                jTree1.expandRow(0);
            }
        }
    }
}

// Lớp Renderer dùng để customize lại JTree
class MyCellRenderer extends DefaultTreeCellRenderer {
    private static final ImageIcon iconRun = new ImageIcon("resource/tool/down.png");
    private static final ImageIcon iconPause = new ImageIcon("resource/tool/pause.png");
    private static final ImageIcon iconStop = new ImageIcon("resource/tool/stop.png");
    @Override
    public Component getTreeCellRendererComponent(JTree tree, Object value, boolean sel, boolean expanded, boolean leaf, int row, boolean hasFocus) {
        super.getTreeCellRendererComponent(tree, value, sel, expanded, leaf, row, hasFocus);
        Project pj = Main.program.getProject(row - 1);
        if(pj != null) {
            int status = pj.getStatus();
            if(status == Project.RUN)
                setIcon(iconRun);
            if(status == Project.PAUSE)
                setIcon(iconPause);
            if(status == Project.STOP)
                setIcon(iconStop);
        }
        return this;
    }
}